//
// Created by ChenYulu on 2017/4/6.
//

#include "convert.h"

/**
 * 转换为灰度图像
 * @param src
 * @param dst
 * @return
 */
int RGBToGray(Bitmap *src, Bitmap *dst) {
  int ret;
  int n = 0, i, j;
  BYTE r, g, b, gray;

  if (src->bitCount != 24) {
    printf("Error(RGBToGray): The source file must be 24 bit RGB.\n");
    return -1;
  }

  ret = CreateBitmap(dst, src->width, src->height, 8);
  if (ret == -1) {
    printf("Error(RGBToGray): Can't create the image.\n");
    return -1;
  }

  //计算灰度数据
  for (i = 0; i < src->height; i++) {
    n = 0;
    for (j = 0; j < src->width * 3; j++, n++) {
      b = *(src->imageData + src->widthStep * (src->height - 1 - i) + j);
      j++;
      g = *(src->imageData + src->widthStep * (src->height - 1 - i) + j);
      j++;
      r = *(src->imageData + src->widthStep * (src->height - 1 - i) + j);
      gray = (r * 19595 + g * 38469 + b * 7472) >> 16;
      *(dst->imageData + dst->widthStep * (dst->height - 1 - i) + n) = gray;
    }
  }

  return 0;
}


int CopyBMP(Bitmap *src, Bitmap *dst) {
  int ret;
  int n = 0, i, j;
  BYTE pixel;

  if (src->bitCount != 8) {
    printf("Error(CopyBMP): The source file must be 8 bit image.\n");
    return -1;
  }

  ret = CreateBitmap(dst, src->width, src->height, 8);
  if (ret == -1) {
    printf("Error(CopyBMP): Can't create the image.\n");
    ret = -1;
  }

  for (i = 0; i < src->height; i++) {
    for (j = 0; j < src->width; j++, n++) {
      pixel = *(src->imageData + src->widthStep * (src->height - 1 - i) + j);
      *(dst->imageData + dst->widthStep * (dst->height - 1 - i) + j) = pixel;
    }
  }

  return 0;
}




